<template>
  <div class="list-page">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" style="display: flex;justify-content: space-between;width: 100%;">
            <el-form-item label="发生地点" prop="location">
              <el-input v-model="queryParams.location" placeholder="请输入发生地点" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="处理状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="处理状态" clearable>
                <el-option :value="0" label="未处理" />
                <el-option :value="1" label="进行中" />
                <el-option :value="2" label="已控制" />
                <el-option :value="3" label="已关闭" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            </el-form-item>
            <div style="display: flex;justify-content: space-between;width: 100%;">
              <br />
              <div>
                <el-button icon="RefreshRight" @click="resetQuery">刷新</el-button>
                <el-button type="primary" icon="Plus" class="add-button" @click="handleAdd">新增</el-button>
                <el-button type="danger" icon="Delete" :disabled="multipleSelection.length === 0" @click="batchDelete">删除</el-button>
              </div>
            </div>
          </el-form>
        </el-card>
      </div>
    </transition>

    <!-- 列表区域 -->
    <el-card shadow="hover" class="w-full">
      <el-table :data="tableData" border style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="序号" prop="index" width="80" align="center">
          <template #default="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column label="卫生类别" prop="publicHealthWarning.category" min-width="180">
          <template #default="scope">
            {{ getDictLabel('health_category', scope.row.publicHealthWarning?.category) }}
          </template>
        </el-table-column>
        <el-table-column label="发病人数" prop="publicHealthWarning.cases" width="120" align="center"></el-table-column>
        <el-table-column label="临床症状" prop="publicHealthWarning.symptoms" width="250"></el-table-column>
        <el-table-column label="发生时间" prop="publicHealthWarning.occurrenceTime" width="200" align="center"></el-table-column>
        <el-table-column label="发生地点" prop="publicHealthWarning.location" width="250"></el-table-column>
        <el-table-column label="预警级别" prop="earlyWarningInfo.warnLevel" width="200" align="center">
          <template #default="scope">
            <el-tooltip :content="`${scope.row.earlyWarningInfo?.warnLevel}级预警`" placement="top">
              <img :src="getAlertImage(scope.row.earlyWarningInfo?.warnLevel)" style="width: 32px; height: 32px" />
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="处理状态" prop="trafficAccidentWarning.status" width="120" align="center">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.earlyWarningInfo?.status) as any">
              {{ getStatusLabel(scope.row.earlyWarningInfo?.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right" align="center">
          <template #default="scope">
            <el-button size="small" type="primary" link @click="viewDetails(scope.row)">详情</el-button>
            <el-button size="small" type="success" link @click="handlePushNotice(scope.row)"> 同步</el-button>
            <el-button size="small" type="warning" link @click="handleJudgment(scope.row)"> 研判</el-button>
            <el-button size="small" type="danger" link @click="handleDelete(scope.row)" v-perms="['bridge:traffic:remove']"> 删除 </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>

    <!-- 详情弹窗 -->
    <el-dialog v-model="detailVisible" title="公共卫生预警详情" width="800px" center destroy-on-close>
      <template #header>
        <div class="dialog-header">
          <span class="dialog-title">公共卫生预警详情</span>
          <div class="action-buttons">
            <el-button v-if="!isEditing" type="primary" @click="enableEditing" class="edit-btn"><i class="el-icon-edit" /> 编辑 </el-button>
            <el-button v-else type="info" @click="cancelEditing" class="cancel-btn"><i class="el-icon-close" /> 取消 </el-button>
          </div>
        </div>
      </template>
      <el-form :model="editForm" :rules="editRules" ref="editFormRef" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="卫生类别：" prop="publicHealthWarning.category">
              <el-select v-model="editForm.publicHealthWarning.category" placeholder="请选择卫生类别" style="width: 100%" :disabled="!isEditing">
                <el-option v-for="item in healthCategoryDict" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue" />
              </el-select>
            </el-form-item>

            <el-form-item label="临床症状：" prop="publicHealthWarning.symptoms">
              <el-input v-model="editForm.publicHealthWarning.symptoms" type="textarea" :rows="2" :disabled="!isEditing" />
            </el-form-item>

            <el-form-item label="发病原因：" prop="publicHealthWarning.cause">
              <el-input v-model="editForm.publicHealthWarning.cause" type="textarea" :rows="2" :disabled="!isEditing" />
            </el-form-item>

            <el-form-item label="发生时间：">
              <el-input v-model="editForm.publicHealthWarning.occurrenceTime" disabled />
            </el-form-item>

            <el-form-item label="预警级别：" prop="earlyWarningInfo.warnLevel">
              <el-select v-model="editForm.earlyWarningInfo.warnLevel" style="width: 100%" :disabled="!isEditing">
                <el-option v-for="item in warnLevelList" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue" />
              </el-select>
            </el-form-item>

            <el-form-item label="禁航需求：">
              <el-radio-group v-model="editForm.earlyWarningInfo.navigationClosure" :disabled="!isEditing">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="记录：" prop="earlyWarningInfo.result">
              <el-input
                v-model="editForm.earlyWarningInfo.result"
                type="textarea"
                :rows="3"
                placeholder="请输入记录信息"
                :disabled="!isEditing"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="发病人数：" prop="publicHealthWarning.cases">
              <el-input-number
                v-model="editForm.publicHealthWarning.cases"
                :min="0"
                controls-position="right"
                style="width: 100%"
                :disabled="!isEditing"
              />
            </el-form-item>

            <el-form-item label="死亡人数：" prop="publicHealthWarning.deaths">
              <el-input-number
                v-model="editForm.publicHealthWarning.deaths"
                :min="0"
                controls-position="right"
                style="width: 100%"
                :disabled="!isEditing"
              />
            </el-form-item>

            <el-form-item label="措施要求：" prop="publicHealthWarning.measures">
              <el-input v-model="editForm.publicHealthWarning.measures" type="textarea" :rows="3" :disabled="!isEditing" />
            </el-form-item>

            <el-form-item label="预警状态：" prop="earlyWarningInfo.status">
              <el-select v-model="editForm.earlyWarningInfo.status" style="width: 100%" :disabled="!isEditing">
                <el-option :value="0" label="未处理" />
                <el-option :value="1" label="进行中" />
                <el-option :value="2" label="已控制" />
                <el-option :value="3" label="已关闭" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <el-button v-if="isEditing" type="primary" @click="handleSubmit" class="save-btn"
          ><i class="el-icon-check" />
          保存修改
        </el-button>
        <el-button @click="detailVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 新增弹窗 -->
    <el-dialog v-model="addDialogVisible" width="80%" top="5vh" destroy-on-close class="add-dialog" :show-header="false">
      <AddComponent @success="handleAddSuccess" />
    </el-dialog>

    <!-- 推送通知弹窗 -->
    <el-dialog v-model="noticeDialog.visible" title="推送预警通知" width="800px" destroy-on-close>
      <el-form ref="noticeFormRef" :model="noticeForm" :rules="noticeRules" label-width="100px">
        <el-form-item label="通知标题" prop="title">
          <el-input v-model="noticeForm.title" placeholder="请输入通知标题" />
        </el-form-item>
        <el-form-item label="通知内容" prop="content">
          <el-input v-model="noticeForm.content" type="textarea" :rows="8" placeholder="请输入通知内容" />
        </el-form-item>
        <el-form-item label="通知方式" prop="notifyMethod">
          <el-select v-model="noticeForm.notifyMethod" placeholder="请选择通知方式" style="width: 100%" multiple>
            <el-option v-for="dict in notifyMethodOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="推送对象" prop="notifyTargets">
          <el-select v-model="noticeForm.notifyTargets" placeholder="请选择推送对象" style="width: 100%" multiple>
            <el-option v-for="target in notifyTargetOptions" :key="target.value" :label="target.label" :value="target.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitNoticeForm">确 定</el-button>
          <el-button @click="noticeDialog.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加研判弹窗 -->
    <el-dialog v-model="judgmentDialog.visible" title="预警研判" width="900px" destroy-on-close class="judgment-dialog">
      <el-form ref="judgmentFormRef" :model="judgmentForm" :rules="judgmentRules" label-width="120px">
        <!-- 第一个板块：预警信息 -->
        <div class="judgment-section info-section">
          <h3 class="section-title">
            <el-icon>
              <InfoFilled />
            </el-icon>
            预警信息
          </h3>
          <el-divider></el-divider>
          <div class="info-display">
            <el-row :gutter="20">
              <el-col :span="12">
                <div class="info-row" v-if="currentWarning.publicHealthWarning">
                  <span class="info-label">卫生类别：</span>
                  <span class="info-value">{{ getDictLabel('health_category', currentWarning.publicHealthWarning.category) }}</span>
                </div>
                <div class="info-row" v-if="currentWarning.publicHealthWarning">
                  <span class="info-label">发生地点：</span>
                  <span class="info-value">{{ currentWarning.publicHealthWarning.location }}</span>
                </div>
                <div class="info-row" v-if="currentWarning.publicHealthWarning">
                  <span class="info-label">发生时间：</span>
                  <span class="info-value">{{ dayjs(currentWarning.publicHealthWarning.occurrenceTime).format('YYYY-MM-DD HH:mm') }}</span>
                </div>
                <div class="info-row" v-if="currentWarning.earlyWarningInfo">
                  <span class="info-label">处理状态：</span>
                  <span class="info-value">
                    <el-tag :type="getStatusType(currentWarning.earlyWarningInfo.status) as any" size="small">
                      {{ getStatusLabel(currentWarning.earlyWarningInfo.status) }}
                    </el-tag>
                  </span>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="info-row" v-if="currentWarning.publicHealthWarning">
                  <span class="info-label">临床症状：</span>
                  <span class="info-value">{{ currentWarning.publicHealthWarning.symptoms }}</span>
                </div>
                <div class="info-row" v-if="currentWarning.publicHealthWarning">
                  <span class="info-label">发病人数：</span>
                  <span class="info-value">{{ currentWarning.publicHealthWarning.cases }}人</span>
                </div>
                <div class="info-row" v-if="currentWarning.earlyWarningInfo">
                  <span class="info-label">预警级别：</span>
                  <span class="info-value">
                    <el-tag :type="getWarnLevelType(currentWarning.earlyWarningInfo.warnLevel)" size="small">
                      {{ currentWarning.earlyWarningInfo.warnLevel }}级预警
                    </el-tag>
                  </span>
                </div>
              </el-col>
            </el-row>
          </div>
        </div>

        <!-- 第二个板块：预警研判 -->
        <div class="judgment-section">
          <h3 class="section-title">
            <el-icon>
              <Warning />
            </el-icon>
            预警研判
          </h3>
          <el-divider></el-divider>

          <el-form-item label="预警级别" prop="eventLevel">
            <el-select v-model="judgmentForm.eventLevel" placeholder="请选择预警级别" style="width: 100%">
              <el-option v-for="item in warnLevelList" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue" />
            </el-select>
          </el-form-item>

          <el-form-item label="研判结果" prop="judgmentResult">
            <el-radio-group v-model="judgmentForm.judgmentResult">
              <el-radio :label="1">转为应急事件</el-radio>
              <el-radio :label="0">无需转为应急事件</el-radio>
            </el-radio-group>
          </el-form-item>
        </div>

        <!-- 第三个板块：预警转事件（仅当选择转为应急事件时显示） -->
        <div class="judgment-section" v-if="judgmentForm.judgmentResult === 1">
          <h3 class="section-title">
            <el-icon>
              <Bell />
            </el-icon>
            预警转事件
          </h3>
          <el-divider></el-divider>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="事件标题" prop="title">
                <el-input v-model="judgmentForm.title" placeholder="请输入事件标题" />
              </el-form-item>

              <el-form-item label="发生时间" prop="happenTime">
                <el-date-picker
                  v-model="judgmentForm.happenTime"
                  type="datetime"
                  placeholder="选择发生时间"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  style="width: 100%"
                />
              </el-form-item>

              <el-form-item label="发生地点" prop="location">
                <el-input v-model="judgmentForm.location" placeholder="请输入发生地点" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="首次报告时间" prop="firstReportTime">
                <el-date-picker
                  v-model="judgmentForm.firstReportTime"
                  type="datetime"
                  placeholder="选择首次报告时间"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  style="width: 100%"
                />
              </el-form-item>

              <el-form-item label="处置状态" prop="status">
                <el-select v-model="judgmentForm.status" placeholder="请选择处置状态" style="width: 100%">
                  <el-option :value="1" label="未启动" />
                  <el-option :value="2" label="进行中" />
                  <el-option :value="3" label="已控制" />
                  <el-option :value="4" label="已关闭" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="事件描述" prop="description">
            <el-input type="textarea" v-model="judgmentForm.description" :rows="3" placeholder="请输入事件描述" />
          </el-form-item>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="judgmentDialog.visible = false">取 消</el-button>
          <el-button type="primary" @click="submitJudgmentForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, defineAsyncComponent, reactive, onMounted, getCurrentInstance, type ComponentInternalInstance, toRefs } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { listData } from '@/api/system/dict/data';
import { DictDataQuery } from '@/api/system/dict/data/types';
import {
  getPublicHealthWarningList,
  getPublicHealthWarningById,
  updatePublicHealthWarning,
  deletePublicHealthWarning,
  deletePublicHealthWarningBatch
} from '@/api/bridge/traffic/publicHealth';
import dayjs from 'dayjs';
import { useRouter, useRoute } from 'vue-router';
import { addNotice, publishNotice } from '@/api/bridge/command/notice';
import { addEmergencyEvent } from '@/api/bridge/command/event';
import useUserStore from '@/store/modules/user';
import { InfoFilled, Warning, Bell, RefreshRight } from '@element-plus/icons-vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { yjcl } = toRefs<any>(proxy?.useDict('yjcl'));

// 添加类型定义
interface PublicHealthWarning {
  id?: string;
  category: string;
  location: string;
  occurrenceTime: string;
  symptoms: string;
  cases: number;
  deaths: number;
  transmissionRoute: string;
  preventiveMeasures: string;
  result: string;
}

interface EarlyWarningInfoType {
  id?: string;
  title?: string;
  warnLevel?: string;
  navigationClosure?: number;
  status?: number;
  result?: string;
}

interface WarningData {
  publicHealthWarning: PublicHealthWarning;
  earlyWarningInfo: EarlyWarningInfoType;
}

interface JudgmentFormType {
  judgmentResult: number;
  eventLevel: string;
  title: string;
  happenTime: string;
  location: string;
  firstReportTime: string;
  status: number;
  description: string;
  warningId: string;
  eventType: string;
}

const showSearch = ref(true);

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  type: null,
  location: null,
  status: null,
  title: null
});

const DictQueryParams = ref<DictDataQuery>({
  dictType: '',
  pageNum: 1,
  pageSize: 10,
  dictName: '',
  dictLabel: ''
});

const tableData = ref([]);
const getList = async () => {
  try {
    const res = await getPublicHealthWarningList(queryParams);
    tableData.value = res.rows;
    total.value = res.total;
  } catch (error) {
    console.error('获取数据失败:', error);
  }
};

// 分类选择
const filterType = ref('全部');
// 搜索值
const searchValue = ref('');
// 当前页码
const currentPage = ref(1);
// 每页数量
const pageSize = ref(10);
// 总数量
const total = ref(0);

const detailVisible = ref(false);
const currentDetail = ref<any>({});

// 在script部分新增表单数据和校验规则
const editForm = ref({
  earlyWarningInfo: {
    title: currentDetail.value.earlyWarningInfo?.title,
    warnLevel: currentDetail.value.earlyWarningInfo?.warnLevel,
    navigationClosure: currentDetail.value.earlyWarningInfo?.navigationClosure,
    status: currentDetail.value.earlyWarningInfo?.status,
    result: currentDetail.value.earlyWarningInfo?.result
  },
  publicHealthWarning: {
    category: '',
    location: '',
    occurrenceTime: '',
    symptoms: '',
    cause: '',
    cases: null,
    deaths: null,
    measures: '',
    result: ''
  }
});

const editRules = ref<any>({
  'publicHealthWarning.category': [{ required: true, message: '请选择卫生类别', trigger: 'change' }],
  'publicHealthWarning.symptoms': [{ required: true, message: '请输入临床症状', trigger: 'blur' }],
  'publicHealthWarning.cause': [{ required: true, message: '请输入发病原因', trigger: 'blur' }],
  'earlyWarningInfo.warnLevel': [{ required: true, message: '请选择预警级别', trigger: 'change' }],
  'earlyWarningInfo.navigationClosure': [{ required: true, message: '请选择禁航需求', trigger: 'change' }],
  'earlyWarningInfo.status': [{ required: true, message: '请选择预警状态', trigger: 'change' }],
  'earlyWarningInfo.result': [{ required: true, message: '请输入记录信息', trigger: 'blur' }]
});

const queryFormRef = ref<any>(null);

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};

const resetQuery = () => {
  // 在这里添加重置逻辑
  queryParams.location = null;
  queryFormRef.value?.resetFields();
  // 调用查询接口
  getList();
};

// 查看详情方法
const viewDetails = async (row: any) => {
  isEditing.value = false;
  try {
    const res = await getPublicHealthWarningById(row.publicHealthWarning.id);
    currentDetail.value = res.data;
    editForm.value = {
      earlyWarningInfo: res.data.earlyWarningInfo,
      publicHealthWarning: res.data.publicHealthWarning
    };
    detailVisible.value = true;
  } catch (error) {
    ElMessage.error('获取详情失败');
  }
};

// 处理事件方法
const handleEvent = (row: any) => {
  console.log('处理事件', row);
};

// 查看结果方法
const viewResult = (row: any) => {
  console.log('查看结果', row);
};

// 修改分页处理方法
const handlePageChange = (val: number) => {
  currentPage.value = val;
  DictQueryParams.value.pageNum = val; // 同步到查询参数
  getList();
};

const handleSizeChange = (val: number) => {
  pageSize.value = val;
  DictQueryParams.value.pageSize = val; // 同步到查询参数
  getList();
};

// 添加搜索和筛选的监听
watch([filterType, searchValue], () => {
  currentPage.value = 1; // 重置为第一页
  DictQueryParams.value.pageNum = 1;
  getList();
});

// 删除处理
const handleDelete = (row: any) => {
  ElMessageBox.confirm('确定要删除该条预警吗？', '警告', {
    type: 'warning'
  })
    .then(async () => {
      await deletePublicHealthWarning(row.publicHealthWarning.id);
      ElMessage.success('删除成功');
      getList();
    })
    .catch(() => {});
};

// 添加新增处理方法
const router = useRouter();

const AddComponent = defineAsyncComponent(() => import('@/views/Bridge/traffic-accident/health.vue'));
const addDialogVisible = ref(false);

const handleAdd = () => {
  addDialogVisible.value = true;
};

const handleAddSuccess = () => {
  addDialogVisible.value = false;
  getList();
  ElMessage.success('新增成功');
};

const accidentTypeDict = ref<any[]>([]); // 事故类型字典
const blockageCauseDict = ref<any[]>([]); // 发生原因字典
const warnLevelList = ref<any[]>([]);
const healthCategoryDict = ref<any[]>([]); // 新增卫生类别字典

// 获取事故类型字典
const getAccidentTypeDict = async () => {
  DictQueryParams.value.dictType = 'accident_type';
  const res = await listData(DictQueryParams.value);
  accidentTypeDict.value = res.rows;
};

// 获取发生原因字典
const getBlockageCauseDict = async () => {
  DictQueryParams.value.dictType = 'blockage_range';
  const res = await listData(DictQueryParams.value);
  blockageCauseDict.value = res.rows;
};

// 获取预警级别字典
const getWarnLevelDict = async () => {
  DictQueryParams.value.dictType = 'warn_level';
  const res = await listData(DictQueryParams.value);
  warnLevelList.value = res.rows;
};

// 获取卫生类别字典
const getHealthCategoryDict = async () => {
  DictQueryParams.value.dictType = 'health_category';
  const res = await listData(DictQueryParams.value);
  healthCategoryDict.value = res.rows;
};

// 修改字典获取方法
const getDictLabel = (dictType: string, value: string) => {
  const dictMap = {
    'health_category': healthCategoryDict.value,
    'warn_level': warnLevelList.value
  };
  const dict = dictMap[dictType] || [];
  const item = dict.find((d: any) => d.dictValue === value);
  return item?.dictLabel || 'N/A';
};

// 添加预警图片获取方法
const getAlertImage = (level: string) => {
  return new URL(`/src/assets/svg/alert${level}.svg`, import.meta.url).href;
};

// 新增提交方法
const handleSubmit = async () => {
  try {
    const submitData = {
      earlyWarningInfo: editForm.value.earlyWarningInfo,
      publicHealthWarning: editForm.value.publicHealthWarning
    };

    const originalStatus = originalData.value.earlyWarningInfo?.status;
    const newStatus = editForm.value.earlyWarningInfo.status;

    await updatePublicHealthWarning(submitData);

    // 如果状态发生改变，询问是否发送通知
    if (originalStatus !== newStatus) {
      ElMessageBox.confirm('您修改了处理状态，是否发送通知？', '提示', {
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'warning'
      })
        .then(() => {
          handlePushNotice(currentDetail.value);
        })
        .catch(() => {});
    }

    ElMessage.success('更新成功');
    await getList();
    detailVisible.value = false;
  } catch (error) {
    ElMessage.error('更新失败');
  }
};

// 添加到 onMounted 或初始化调用
getAccidentTypeDict();
getBlockageCauseDict();
getWarnLevelDict();
getHealthCategoryDict();
getList();

// 在script部分添加状态控制
const isEditing = ref(false);
const originalData = ref({});

const enableEditing = () => {
  isEditing.value = true;
  if (!originalData.value.earlyWarningInfo) {
    originalData.value = {
      earlyWarningInfo: {},
      publicHealthWarning: {}
    };
  }
  originalData.value = JSON.parse(JSON.stringify(editForm.value));
};

const cancelEditing = () => {
  isEditing.value = false;
  editForm.value = JSON.parse(JSON.stringify(originalData.value));
};

const route = useRoute();
const userStore = useUserStore();

// 添加当前行数据的响应式引用
const currentRow = ref<any>(null);

// 通知相关数据
const noticeDialog = ref({
  visible: false,
  title: '推送预警通知'
});

const noticeFormRef = ref();
const noticeForm = ref({
  title: '',
  content: '',
  warnType: '4', // 公共卫生预警
  status: 1,
  notifyMethod: [],
  notifyTargets: [], // 新增推送对象字段
  sendTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
  userId: userStore.userId,
  warnLevel: ''
});

const noticeRules = {
  title: [{ required: true, message: '请输入通知标题', trigger: 'blur' }],
  content: [{ required: true, message: '请输入通知内容', trigger: 'blur' }],
  notifyMethod: [{ required: true, message: '请选择通知方式', trigger: 'change' }],
  notifyTargets: [{ required: true, message: '请选择推送对象', trigger: 'change' }]
};

// 通知方式字典
const notifyMethodOptions = ref([]);

// 获取通知方式字典
const getNotifyMethodDict = async () => {
  const res = await listData({
    dictType: 'notification_method',
    pageNum: 1,
    pageSize: 100,
    dictName: '',
    dictLabel: ''
  });
  notifyMethodOptions.value = res.rows || [];
};

// 格式化通知内容
const formatNoticeContent = (row: any) => {
  const content = [
    `卫生类别：${getDictLabel('health_category', row.publicHealthWarning?.category)}`,
    `发病人数：${row.publicHealthWarning?.cases}人`,
    `临床症状：${row.publicHealthWarning?.symptoms}`,
    `发生地点：${row.publicHealthWarning?.location}`,
    `预警级别：${row.earlyWarningInfo?.warnLevel}级预警`,
    `处理状态：${row.earlyWarningInfo?.status ? '已处理' : '未处理'}`
  ].join('\n');
  return content;
};

// 处理推送通知
const handlePushNotice = (row: any) => {
  currentRow.value = row;
  noticeForm.value = {
    title: '公共卫生预警通知',
    content: formatNoticeContent(row),
    warnType: '4',
    status: 1,
    notifyMethod: [],
    notifyTargets: [],
    sendTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    userId: userStore.userId,
    warnLevel: row.earlyWarningInfo.warnLevel
  };
  noticeDialog.value.visible = true;
};

// 提交通知表单
const submitNoticeForm = async () => {
  if (!noticeFormRef.value) return;

  await noticeFormRef.value.validate();

  try {
    const submitData = {
      ...noticeForm.value,
      notifyMethod: Array.isArray(noticeForm.value.notifyMethod) ? noticeForm.value.notifyMethod.join(',') : noticeForm.value.notifyMethod
    };

    const res = await addNotice(submitData);
    if (res.code === 200) {
      await publishNotice(res.data);
      ElMessage.success('通知已同步');
      noticeDialog.value.visible = false;
    }
  } catch (error) {
    console.error('推送失败:', error);
    ElMessage.error('推送失败');
  }
};

// 添加推送对象选项
const notifyTargetOptions = ref([
  { label: '大桥管理局', value: 'bridge_admin' },
  { label: '卫生管理局', value: 'health_admin' },
  { label: '中交公规院', value: 'traffic_institute' },
  { label: '海事局', value: 'maritime_admin' }
]);

// 添加研判相关变量和方法
const judgmentDialog = reactive({
  visible: false
});

const judgmentFormRef = ref();
const judgmentForm = ref<JudgmentFormType>({
  judgmentResult: 0,
  eventLevel: '',
  title: '',
  happenTime: '',
  location: '',
  firstReportTime: '',
  status: 1,
  description: '',
  warningId: '',
  eventType: 'health'
});

const judgmentRules = {
  eventLevel: [{ required: true, message: '请选择预警级别', trigger: 'change' }],
  judgmentResult: [{ required: true, message: '请选择研判结果', trigger: 'change' }],
  title: [{ required: true, message: '请输入事件标题', trigger: 'blur' }],
  happenTime: [{ required: true, message: '请选择发生时间', trigger: 'change' }],
  location: [{ required: true, message: '请输入发生地点', trigger: 'blur' }],
  firstReportTime: [{ required: true, message: '请选择首次报告时间', trigger: 'change' }],
  status: [{ required: true, message: '请选择处置状态', trigger: 'change' }],
  description: [{ required: true, message: '请输入事件描述', trigger: 'blur' }]
};

// 处理研判方法
const handleJudgment = (row: any) => {
  // 设置当前预警信息
  currentWarning.value = row;

  judgmentForm.value = {
    judgmentResult: 0,
    eventLevel: row.earlyWarningInfo?.warnLevel || '',
    title: `公共卫生事件-${getDictLabel('health_category', row.publicHealthWarning?.category)}`,
    happenTime: row.publicHealthWarning?.occurrenceTime || '',
    location: row.publicHealthWarning?.location || '',
    firstReportTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    status: 1,
    description: `${getDictLabel('health_category', row.publicHealthWarning?.category)}，临床症状: ${row.publicHealthWarning?.symptoms}，发病人数: ${row.publicHealthWarning?.cases}人`,
    warningId: row.publicHealthWarning?.id,
    eventType: 'health'
  };
  judgmentDialog.visible = true;
};

// 提交研判表单
const submitJudgmentForm = async () => {
  if (!judgmentFormRef.value) return;

  try {
    await judgmentFormRef.value.validate();

    if (judgmentForm.value.judgmentResult === 1) {
      // 转为应急事件
      const eventData = {
        title: judgmentForm.value.title,
        location: judgmentForm.value.location,
        status: judgmentForm.value.status,
        happenTime: judgmentForm.value.happenTime,
        firstReportTime: judgmentForm.value.firstReportTime,
        description: judgmentForm.value.description,
        warningId: judgmentForm.value.warningId
      };

      await addEmergencyEvent(eventData);
      ElMessage.success('已成功转为应急事件');
    } else {
      ElMessage.success('研判完成');
    }

    judgmentDialog.visible = false;
  } catch (error) {
    console.error('研判失败:', error);
    ElMessage.error('研判失败');
  }
};

// 当前预警信息
const currentWarning = ref({
  publicHealthWarning: {
    category: '',
    cases: 0,
    symptoms: '',
    occurrenceTime: '',
    location: '',
    spreadRate: '',
    controlMeasures: ''
  },
  earlyWarningInfo: {
    title: '',
    warnLevel: '',
    navigationClosure: 0,
    status: 0
  }
});

// 预警级别类型获取
const getWarnLevelType = (level) => {
  const levelMap = {
    '1': 'danger', // 一级预警 - 红色
    '2': 'warning', // 二级预警 - 橙色
    '3': 'success', // 三级预警 - 黄色
    '4': 'info' // 四级预警 - 蓝色
  };
  return levelMap[level] || 'info';
};

// 多选相关
const multipleSelection = ref<any[]>([]);

// 表格多选框选中事件处理
const handleSelectionChange = (selection: any[]) => {
  multipleSelection.value = selection;
};

// 批量删除
const batchDelete = () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请选择要删除的数据');
    return;
  }
  
  // 获取选中行的ID列表
  const ids = multipleSelection.value.map(item => {
    return item.publicHealthWarning?.id || item.earlyWarningInfo?.id || item.id;
  }).join(',');
  
  ElMessageBox.confirm('确定要删除选中的数据吗？', '警告', {
    type: 'warning'
  })
    .then(async () => {
      await deletePublicHealthWarningBatch(ids);
      ElMessage.success('批量删除成功');
      // 清空选中项
      multipleSelection.value = [];
      // 刷新列表数据
      await getList();
    })
    .catch(() => {});
};

const getStatusType = (status: number): 'warning' | 'primary' | 'success' | 'info' => {
  const statusMap: Record<number, 'warning' | 'primary' | 'success' | 'info'> = {
    0: 'warning',
    1: 'primary',
    2: 'success',
    3: 'info'
  };
  return statusMap[status] || 'warning';
};

const getStatusLabel = (status: number) => {
  const statusMap: Record<number, string> = {
    0: '未处理',
    1: '进行中',
    2: '已控制',
    3: '已关闭'
  };
  return statusMap[status] || '未处理';
};

onMounted(() => {
  getAccidentTypeDict();
  getBlockageCauseDict();
  getWarnLevelDict();
  getNotifyMethodDict(); // 添加获取通知方式字典
  getList();
});
</script>

<style scoped lang="scss">
$padding: 20px;
$background-color-page: var(--el-bg-color-page);
$background-color-overlay: var(--el-bg-color-overlay);
$box-shadow-light: var(--el-box-shadow-light);
$border-radius: 4px;
$border-color-light: var(--el-border-color-light);
$transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

.list-page {
  padding: $padding;
  background: $background-color-page;
  border-radius: $border-radius;
  box-shadow: $box-shadow-light;
}

.filter-area,
.pagination-container,
.detail-container,
.dialog-header,
.el-dialog,
.judgment-section,
.refresh-button {
  background: $background-color-overlay;
  padding: $padding;
  border-radius: $border-radius;
}

.filter-area {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 20px;

  .search-input {
    width: 300px;
    margin-left: auto;
  }
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.el-table {
  margin-top: 16px;

  :deep(th) {
    background: $background-color-page !important;
  }

  :deep(.warning-row) {
    --el-table-tr-bg-color: var(--el-color-warning-light-9);
  }

  :deep(.success-row) {
    --el-table-tr-bg-color: var(--el-color-success-light-9);
  }
}

.detail-container {
  display: flex;
  gap: 30px;
  padding: $padding 0;

  .detail-column {
    flex: 1;
    min-width: 300px;

    .detail-title {
      color: #409eff;
      font-size: 16px;
      margin-bottom: 15px;
      padding-bottom: 8px;
      border-bottom: 1px solid #ebeef5;
    }

    .detail-row {
      margin-bottom: 12px;
      display: flex;
      line-height: 1.6;

      .detail-label,
      .info-label {
        width: 120px;
        color: #909399;
        font-weight: 500;
        flex-shrink: 0;
      }

      .detail-value,
      .info-value {
        flex: 1;
        color: #303133;
        word-break: break-word;
      }
    }
  }

  .unit {
    margin-left: 8px;
    color: #909399;
    font-size: 12px;
  }

  .el-input-number,
  .el-date-editor,
  .el-radio-group {
    width: 100%;
  }

  .el-input-number {
    :deep(.el-input__inner) {
      text-align: left;
    }
  }

  .el-radio-group {
    margin-top: 8px;
  }
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: $background-color-page;
  border-radius: $border-radius;
  border-bottom: 1px solid $border-color-light;

  .dialog-title {
    font-size: 18px;
    color: #303133;
    font-weight: 600;
  }

  .action-buttons {
    display: flex;
    gap: 12px;
  }
}

.edit-btn,
.cancel-btn,
.save-btn {
  transition: $transition;
  padding: 10px 20px;
  border-radius: $border-radius;
}

.edit-btn {
  &:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  }
}

.cancel-btn {
  &:hover {
    background-color: #f4f4f5;
    color: #909399;
  }
}

.save-btn {
  padding: 10px 24px;

  &:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);
  }
}

.disabled-field {
  :deep(.el-input__inner) {
    background-color: #f8f9fa;
    border-color: #e4e7ed;
    color: #909399;
    cursor: not-allowed;
  }
}

.el-dialog {
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);

  &__body {
    padding: 24px;
    background: $background-color-overlay;
  }
}

.el-form-item {
  margin-bottom: 24px;

  :deep(.el-form-item__label) {
    color: #606266;
    font-weight: 500;
  }
}

.unit {
  margin-left: 10px;
  color: #909399;
  font-size: 14px;
  font-style: italic;
}

.add-dialog {
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);

  &__body {
    padding: 24px;
    background: $background-color-overlay;
  }
}

.judgment-section {
  background-color: $background-color-overlay;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);

  .section-title {
    font-size: 18px;
    color: #409eff;
    font-weight: 600;
    margin-bottom: 10px;
    display: flex;
    align-items: center;
    gap: 8px;

    .el-icon {
      margin-right: 8px;
      font-size: 20px;
    }
  }

  .info-display {
    margin-top: 15px;

    .info-row {
      margin-bottom: 12px;
      display: flex;
      line-height: 1.6;
    }
  }
}

.info-section {
  background-color: rgba(64, 158, 255, 0.05);
  border-left: 4px solid #409eff;
}

.judgment-dialog {
  :deep(.el-dialog) {
    border-radius: 8px;
    box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
    overflow: hidden;

    .el-dialog__header {
      background: linear-gradient(to right, #409eff, #67c23a);
      padding: 15px 20px;

      .el-dialog__title {
        color: white;
        font-size: 18px;
        font-weight: 600;
      }

      .el-dialog__headerbtn {
        top: 15px;

        .el-dialog__close {
          color: white;
        }
      }
    }

    .el-dialog__body {
      padding: 20px;
    }

    .el-dialog__footer {
      padding: 10px 20px;
      border-top: 1px solid #f0f0f0;
    }
  }
}

.refresh-button {
  transition: all 0.3s ease;

  &:hover {
    transform: rotate(180deg);
  }
}
</style>
